<?php


namespace app\admin\pms\logic;


use app\common\logic\BaseLogic;
use app\model\pms\Goods;
use app\model\pms\GoodsSku;
use app\model\pms\GoodsSpec;
use support\exception\BadException;
use support\utils\Time;

class GoodsLogic extends BaseLogic
{


    public function __construct()
    {
        $this->model = new Goods();
    }

    public function addGoods($input)
    {
        $skuPrice = array_column($input['skuList'] ?? [], 'price');

        if ($input['spec'] == 2) {
            $min_price = count($skuPrice) > 1 ? min($skuPrice) : ($skuPrice[0] ?? ['price']);
            $max_price = count($skuPrice) > 1 ? max($skuPrice) : ($skuPrice[0] ?? ['price']);
        } else {
            $min_price = $input['price'];
            $max_price = $input['price'];
        }

        $insertGoods = [
            "type" => $input['type'] ?? "1",
            "name" => $input['name'] ?? "",
            "sub_name" => $input['sub_name'] ?? "",
            "cate_id1" => $input['cate_id1'] ?? "",
            "cate_id2" => $input['cate_id2'] ?? "",
            "cate_id3" => $input['cate_id3'] ?? "",
            "brand_id" => $input['brand_id'] ?? "",
            "unit" => $input['unit'] ?? "",
            "slider_image" => $input['slider_image'] ?? [],
            "attr" => $input['attr'] ?? [],
            "main_image" => $input['slider_image'][0] ?? "",
            "min_price" => $min_price,
            "max_price" => $max_price,
            "shipping_tpl_id" => $input['shipping_tpl_id'] ?? 0,
            "freight_type" => $input['freight_type'] ?? 1,
            "freight" => $input['freight'] ?? 0,
            "tag_ids" => $input['tag_ids'] ?? [],
            "video_src" => $input['video_src'] ?? "",
            "content" => $input['content'] ?? "",
            "spec" => $input['spec'] ?? "1",
            "create_time" => Time::now(),
        ];
        $model = new Goods();
        $model->save($insertGoods);
        $goods_id = $model->id;
//        $goods_id = $this->model->insertGetId($insertGoods);
        $insertGoodsSku = [];
        //单规格
        if ($insertGoods['spec'] == 1) {
            $insertGoodsSku[] = [
                "goods_id" => $goods_id,
                "sku_name" => "默认",
                "image" => $insertGoods['image'] ?? 0,
                "bar_code" => $input['bar_code'] ?? 0,
                "price" => $input['price'] ?? 0,
                "cost_price" => $input['cost_price'] ?? 0,
                "original_price" => $input['original_price'] ?? 0,
                "spu" => $input['spu'] ?? 0,
                "stock" => $input['stock'] ?? 0,
                "weight" => $input['weight'] ?? 0,
                "volume" => $input['volume'] ?? 0,
            ];
        }
        //多规格
        if ($insertGoods['spec'] == 2) {
            $skuList = $input['skuList'] ?? [];
            if (!$skuList) {
                throw new BadException("请输入规格");
            }
            foreach ($skuList as $value) {
                $insertGoodsSku[] = [
                    "goods_id" => $goods_id,
                    "sku_name" => GoodsSkuLogic::skuNameTo(GoodsSkuLogic::FRONT_END, GoodsSkuLogic::BACKED, $value['sku_name'] ?? ""),
                    "stock" => $value['stock'] ?? 0,
                    "price" => $value['price'] ?? 0,
                    "image" => $value['image'] ?? 0,
                    "cost_price" => $value['cost_price'] ?? 0,
                    "bar_code" => $value['bar_code'] ?? 0,
                    "original_price" => $value['original_price'] ?? 0,
                    "weight" => $value['weight'] ?? 0,
                    "volume" => $value['volume'] ?? 0,
                ];
            }
            $insertGoodsSpec = [
                'goods_id' => $goods_id,
                'spec' => json_encode($input['specValue'] ?? [])
            ];
            GoodsSpec::insert($insertGoodsSpec);
        }
        GoodsSku::insertAll($insertGoodsSku);
        return $goods_id;
    }

    public function editGoods($input)
    {
        $skuPrice = array_column($input['skuList'] ?? [], 'price');
        $goods_id = $input['id'] ?? "";
        if (!$goods_id) {
            throw new BadException("缺少商品ID");
        }

        if ($input['spec'] == 2) {
            $min_price = count($skuPrice) > 1 ? min($skuPrice) : ($skuPrice[0] ?? ['price']);
            $max_price = count($skuPrice) > 1 ? max($skuPrice) : ($skuPrice[0] ?? ['price']);
        } else {
            $min_price = $input['price'];
            $max_price = $input['price'];
        }
        $updateGoods = [
            "type" => $input['type'] ?? "1",
            "name" => $input['name'] ?? "",
            "sub_name" => $input['sub_name'] ?? "",
            "cate_id1" => $input['cate_id1'] ?? "",
            "cate_id2" => $input['cate_id2'] ?? "",
            "cate_id3" => $input['cate_id3'] ?? "",
            "brand_id" => $input['brand_id'] ?? "",
            "main_image" => $input['slider_image'][0] ?? "",
            "attr" => $input['attr'] ?? [],
            "content" => $input['content'] ?? "",
            "min_price" => $min_price,
            "max_price" => $max_price,
            "shipping_tpl_id" => $input['shipping_tpl_id'] ?? 0,
            "freight_type" => $input['freight_type'] ?? 1,
            "freight" => $input['freight'] ?? 0,
            "tag_ids" => $input['tag_ids'] ?? [],
            "unit" => $input['unit'] ?? "",
            "slider_image" => $input['slider_image'] ?? [],
            "video_src" => $input['video_src'] ?? "",
            "spec" => $input['spec'] ?? "1",
        ];
        $one = $this->model->find($goods_id);
        $one->save($updateGoods);
        if ($updateGoods['spec'] == 1) {
            $goodsSku = [
                "goods_id" => $goods_id,
                "sku_name" => "默认",
                "stock" => $input['stock'] ?? 0,
                "price" => $input['price'] ?? 0,
                "image" => $input['slider_image'][0] ?? "",
                "cost_price" => $input['cost_price'] ?? 0,
                "bar_code" => $input['bar_code'] ?? "",
                "original_price" => $input['original_price'] ?? 0,
                "weight" => $input['weight'] ?? 0,
                "volume" => $input['volume'] ?? 0,
            ];
            if (GoodsSku::where(["goods_id" => $goods_id, 'sku_name' => $goodsSku['sku_name']])->count() > 0) {
                GoodsSku::where(["goods_id" => $goods_id, 'sku_name' => $goodsSku['sku_name']])->update($goodsSku);
            } else {
                GoodsSku::insert($goodsSku);
            }
        }
        if ($updateGoods['spec'] == 2) {
            $goodsSku = [];
            $skuList = $input['skuList'] ?? [];
            if (!$skuList) {
                throw new BadException("请输入规格");
            }
            foreach ($skuList as $value) {
                $goodsSku[] = [
                    "goods_id" => $goods_id,
                    "sku_name" => GoodsSkuLogic::skuNameTo(GoodsSkuLogic::FRONT_END, GoodsSkuLogic::BACKED, $value['sku_name'] ?? ""),
                    "stock" => $value['stock'] ?? 0,
                    "price" => $value['price'] ?? 0,
                    "image" => $value['image'] ?? 0,
                    "cost_price" => $value['cost_price'] ?? 0,
                    "bar_code" => $value['bar_code'] ?? 0,
                    "original_price" => $value['original_price'] ?? 0,
                    "weight" => $value['weight'] ?? 0,
                    "volume" => $value['volume'] ?? 0,
                ];
            }
            $oldSku = GoodsSku::where(['goods_id' => $goods_id])->column('sku_name');
            // 存在的则更新，新增的插入，多余的删除
            $sku2Id = [];
            foreach ($oldSku as $vo) {
                $sku2Id[$vo] = $vo;
            }

            $insertMap = [];
            $needDel = $sku2Id;
            foreach ($goodsSku as $vo) {
                if (!isset($sku2Id[$vo['sku_name']])) {
                    $insertMap[] = $vo;
                } else {
                    // 存在的，更新
                    GoodsSku::where(['goods_id' => $goods_id, 'sku_name' => $sku2Id[$vo['sku_name']]])->update($vo);
                    unset($needDel[$vo['sku_name']]);
                }
            }

            // 本次新增的插入
            if (!empty($insertMap)) {
                $res = GoodsSku::insertAll($insertMap);
                if (!$res) {
                    throw new BadException("更新商品sku失败");
                }
            }

            // 已经删除的，则删掉
            if (!empty($needDel)) {
                GoodsSku::where(['goods_id' => $goods_id, 'sku_name' => array_values($needDel)])->delete();
            }
            GoodsSpec::where(['goods_id' => $goods_id])->update(['spec' => json_encode($input['specValue'] ?? [], JSON_UNESCAPED_UNICODE)]);
        }
        return $goods_id;
    }

    public function readGoods($goods_id)
    {
        $one = $this->model->with([
            "cate1",
            "cate2",
            "cate3",
        ])->find($goods_id)->toArray();
        $skuList = GoodsSku::where(['goods_id' => $goods_id])->select()->each(function ($v) {
            $v['sku_name'] = GoodsSkuLogic::skuNameTo(GoodsSkuLogic::BACKED, GoodsSkuLogic::FRONT_END, $v['sku_name'] ?? "");
            return $v;
        });
        if ($one['spec'] == 1) {
            $one = array_merge($one, [
                "stock" => $skuList[0]['stock'] ?? 0,
                "price" => $skuList[0]['price'] ?? 0,
                "image" => $skuList[0]['image'] ?? 0,
                "cost_price" => $skuList[0]['cost_price'] ?? 0,
                "bar_code" => $skuList[0]['bar_code'] ?? 0,
                "original_price" => $skuList[0]['original_price'] ?? 0,
                "weight" => $skuList[0]['weight'] ?? 0,
                "volume" => $skuList[0]['volume'] ?? 0,
                "sku_name" => $skuList[0]['sku_name'] ?? 0,
            ]);
        }

        $one['category_id'] = array_values(array_filter([$one['cate_id1'], $one['cate_id2'], $one['cate_id3']]));
        $one['skuList'] = $skuList;
        $one['specValue'] = json_decode(GoodsSpec::where(['goods_id' => $goods_id])->value("spec"), true);
        return $one;
    }
}